package com.yuerenjf.yuerenjinfu.adapter;

import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.qiniu.android.utils.StringUtils;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.activity.WebActivity;
import com.yuerenjf.yuerenjinfu.bean.LendYouXuanBean;
import com.yuerenjf.yuerenjinfu.listener.OnRecyclerViewItemClickListener;
import com.yuerenjf.yuerenjinfu.widget.DinTextView;

import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.iwgang.countdownview.CountdownView;


/**
 * Created by fengjh on 16/7/19.
 */
public class AdapterLendRecycler extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int STATUS_YURE=1;
    private static final int STATUS_CHUJIE=2;
    private static final int STATUS_YISHOUQING=3;
    private static final int STATUS_JIXIZHONG=4;
    private static final int STATUS_WANBI=5;
    private static final int STATUS_ZHUANRANG=6;




    private static final int TYPE_ITEM = 2;
    private static final int TYPE_EMPTY = 3;
    private View mEmptyView;

    private Context mContext;
    private List<LendYouXuanBean.DataBean.CurBorrowsBean> mLendItems=new ArrayList<>();
    private OnRecyclerViewItemClickListener mOnRecyclerViewItemClickListener;
    private final SparseArray<AdapterLendRecycler.VideoViewHolder> mCountdownVHList;
    private Handler mHandler = new Handler();
    private Timer mTimer;
    private boolean isCancel = true;



    public OnRecyclerViewNoDataClickListener getmOnRecyclerViewNoDataClickListener() {
        return mOnRecyclerViewNoDataClickListener;
    }

    public void setmOnRecyclerViewNoDataClickListener(OnRecyclerViewNoDataClickListener mOnRecyclerViewNoDataClickListener) {
        this.mOnRecyclerViewNoDataClickListener = mOnRecyclerViewNoDataClickListener;
    }

    private OnRecyclerViewNoDataClickListener mOnRecyclerViewNoDataClickListener;

    public AdapterLendRecycler(Context mContext) {
        this.mContext = mContext;
        mCountdownVHList = new SparseArray<>();
    }

    @Override
    public int getItemViewType(int position) {
        int size = mLendItems.size();
        if (size == 0 && null != mEmptyView) {
            return TYPE_EMPTY;
        }
        return TYPE_ITEM;
    }
    public void addDatas(List<LendYouXuanBean.DataBean.CurBorrowsBean> datas) {
        mLendItems.addAll(datas);
        notifyDataSetChanged();
    }
    public void removeDatas() {
        mLendItems.clear();
        notifyDataSetChanged();
    }

    public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
        mOnRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        super.onViewRecycled(holder);
        if(holder instanceof AdapterLendRecycler.VideoViewHolder){
            AdapterLendRecycler.VideoViewHolder homeHolder= (AdapterLendRecycler.VideoViewHolder) holder;
            LendYouXuanBean.DataBean.CurBorrowsBean curAnnounceGoodsInfo = homeHolder.getmItemInfo();
            if (null != curAnnounceGoodsInfo && Long.valueOf(curAnnounceGoodsInfo.getTime_start())-System.currentTimeMillis() > 0) {
                mCountdownVHList.remove(Integer.valueOf(curAnnounceGoodsInfo.getBorrow_id()));
            }

        }
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_lend_youxuan, parent, false);
            return new VideoViewHolder(inflate);
        } else {

            View inflate = mEmptyView;
            EmptyHolder holder= new EmptyHolder(inflate);
            if(inflate!=null){
                RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT);
//                RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) holder.noDataLayout.getLayoutParams();
//                linearParams.height = RelativeLayout.LayoutParams.MATCH_PARENT;
//                linearParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
                holder.noDataLayout.setLayoutParams(params);
//                holder.noDataLayout.setLayoutParams(linearParams, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            }

            return holder;
        }


//
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if (holder instanceof VideoViewHolder) {
            final LendYouXuanBean.DataBean.CurBorrowsBean bean=mLendItems.get(position);
            VideoViewHolder itemHolder= (VideoViewHolder) holder;
            itemHolder.bindData(bean);
            itemHolder.mItem_lend_title.setText(bean.getBorrow_title());
            //抵押债权
            // itemHolder.mItem_lend_diya_status.settext

            //新手专享
            if(bean.getIs_new_hand()!=null&&bean.getIs_new_hand().equals("1")){
                itemHolder.mItem_lend_xinshou_status.setVisibility(View.VISIBLE);
            }else{
                itemHolder.mItem_lend_xinshou_status.setVisibility(View.GONE);
            }
            if(StringUtils.isNullOrEmpty(bean.getAdd_apr_show())){
                itemHolder.mItem_lend_shouyilv_top.setVisibility(View.INVISIBLE);
            }else{
                itemHolder.mItem_lend_shouyilv_top.setVisibility(View.VISIBLE);
                itemHolder.mItem_lend_shouyilv_top.setText(bean.getAdd_apr_show());
            }

            itemHolder.mItem_lend_first_shouyi_text.setText(bean.getApr()+"");
            if (!"0".equals(bean.getAdd_apr())) {
                itemHolder.mItem_lend_second_shouyi_text.setVisibility(View.VISIBLE);
                itemHolder.mItem_lend_second_shouyi_text.setText("+" + bean.getAdd_apr() + "%");
            }else{
                itemHolder.mItem_lend_second_shouyi_text.setVisibility(View.GONE);
            }
            itemHolder.mItem_lend_qixian_text.setText(bean.getTime_limit());
            itemHolder.mItem_lend_qixian_unit_text.setText(bean.getStyle());


            try{
                long account=Long.valueOf(bean.getAccount());
                double acc=account/10000;
                String result = String.format("%.2f", acc);
                itemHolder.mItem_lend_total_text.setText(result+"");
            }catch (Exception e){
                e.printStackTrace();
            }



            itemHolder.mItem_lend_youxuan_last_money_text.setText("剩余"+bean.getNeed_accout()+"元可投");

            itemHolder.mItem_lend_percent_text.setText(bean.getDegree() + "%");
            Double d = Double.valueOf(bean.getDegree());
            long l = Math.round(d);
            int i = Math.round(l);
            itemHolder.mItem_lend_percent_pb.setProgress(i);

            switch (bean.getButton_status()){
                case STATUS_YURE:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.GONE);
                    itemHolder.mCountDownView.setVisibility(View.VISIBLE);
                    long duration = bean.getTime_now() - System.currentTimeMillis() / 1000;//服务器与本地相差秒数
                    bean.setCountdown(duration);


                    long restTime = Long.valueOf(bean.getTime_start()) - bean.getTime_now();
                    Log.i("restTime", Long.valueOf(bean.getTime_start())+"--"+ restTime + "");

                    itemHolder.mCountDownView.setmRemainTime(restTime*1000);
                    LogUtil.i(restTime + "");
                    if (restTime > 0) {
                        synchronized (mCountdownVHList) {
                            mCountdownVHList.put(Integer.valueOf(bean.getBorrow_id()), itemHolder);
                        }
                        startRefreshTime();
                    }else{
                        bean.setButton_status(STATUS_CHUJIE);
                        notifyDataSetChanged();
                    }






                    break;

                case STATUS_CHUJIE:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("立即出借");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);



                    break;


                case STATUS_YISHOUQING:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn_gray);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("已售罄");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;

                case STATUS_JIXIZHONG:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn_gray);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("正在计息中");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;

                case STATUS_WANBI:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn_gray);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("还款已完毕");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;

                case STATUS_ZHUANRANG:
                    itemHolder.mItem_lend_youxuan_sell_status_text.setBackgroundResource(R.drawable.icon_lend_status_btn_gray);
                    itemHolder.mItem_lend_youxuan_sell_status_text.setText("已转让");
                    itemHolder.mItem_lend_youxuan_sell_status_text.setVisibility(View.VISIBLE);
                    itemHolder.mCountDownView.setVisibility(View.GONE);
                    break;




            }

            itemHolder.mItem_lend_youxuan_sell_status_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    WebActivity.launchActivity(mContext,bean.getBorrow_url());
                }
            });

            itemHolder.mCountDownView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    WebActivity.launchActivity(mContext,bean.getBorrow_url());
                }
            });





        } else if (holder instanceof EmptyHolder) {
            final EmptyHolder videoViewHolder = (EmptyHolder) holder;
            videoViewHolder.nodata.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i("click", "click");
                    mOnRecyclerViewNoDataClickListener.onRecyclerViewNoDataClick();
//                    ToastHelper.makeText(mContext, "点击了", Toast.LENGTH_LONG).setAnimation(R.style.Animation_Toast).show();
                }
            });
        }


    }




    public void setEmptyView(View emptyView) {
        mEmptyView = emptyView;
        notifyItemInserted(0);
    }

    public void removeEmptyView() {
        if(mEmptyView!=null){
            notifyItemRemoved(0);
            mEmptyView = null;
        }

    }

    @Override
    public int getItemCount() {
        int count = 0;
        int size = mLendItems.size();
        if (size == 0 && null != mEmptyView) {
            count = 1;
        }else{
            count=size;
        }
        return count;
    }

    public class VideoViewHolder extends RecyclerView.ViewHolder {
        private TextView mItem_lend_diya_status;
        private TextView mItem_lend_xinshou_status;
        private TextView mItem_lend_title;
        private TextView mItem_lend_shouyilv_top;
        private DinTextView mItem_lend_first_shouyi_text;
        private DinTextView mItem_lend_second_shouyi_text;
        private TextView mItem_lend_total_text;
        private TextView mItem_lend_total_unit_text;
        private TextView mItem_lend_youxuan_last_money_text;
        private ProgressBar mItem_lend_percent_pb;
        private TextView mItem_lend_youxuan_sell_status_text;


        private DinTextView mItem_lend_qixian_text;
        private TextView mItem_lend_qixian_unit_text;
        private TextView mItem_lend_percent_text;

        public CountdownView getmCountDownView() {
            return mCountDownView;
        }

        public void setmCountDownView(CountdownView mCountDownView) {
            this.mCountDownView = mCountDownView;
        }

        private CountdownView mCountDownView;
        LendYouXuanBean.DataBean.CurBorrowsBean mItemInfo;

        public LendYouXuanBean.DataBean.CurBorrowsBean getmItemInfo() {
            return mItemInfo;
        }

        public void setmItemInfo(LendYouXuanBean.DataBean.CurBorrowsBean mItemInfo) {
            this.mItemInfo = mItemInfo;
        }
        public VideoViewHolder(View itemView) {
            super(itemView);

                mItem_lend_diya_status = (TextView) itemView.findViewById(R.id.item_lend_diya_status);
                mItem_lend_xinshou_status = (TextView) itemView.findViewById(R.id.item_lend_xinshou_status);
                mItem_lend_title = (TextView) itemView.findViewById(R.id.item_lend_title);
                mItem_lend_shouyilv_top = (TextView) itemView.findViewById(R.id.item_lend_shouyilv_top);
                mItem_lend_first_shouyi_text = (DinTextView) itemView.findViewById(R.id.item_lend_first_shouyi_tv);
                mItem_lend_second_shouyi_text = (DinTextView) itemView.findViewById(R.id.item_lend_second_shouyi_text);
                mItem_lend_total_text = (TextView) itemView.findViewById(R.id.item_lend_total_text);
                mItem_lend_total_unit_text = (TextView) itemView.findViewById(R.id.item_lend_total_unit_text);
                mItem_lend_youxuan_last_money_text = (TextView) itemView.findViewById(R.id.item_lend_youxuan_last_money_text);
                mItem_lend_percent_pb = (ProgressBar) itemView.findViewById(R.id.pb_newlevel);
                mItem_lend_youxuan_sell_status_text = (TextView) itemView.findViewById(R.id.item_lend_youxuan_sell_status_text);

            mItem_lend_qixian_text= (DinTextView) itemView.findViewById(R.id.item_lend_qixian_tv);
            mItem_lend_qixian_unit_text= (TextView) itemView.findViewById(R.id.item_lend_qixian_unit_tv);
            mItem_lend_percent_text= (TextView) itemView.findViewById(R.id.item_lend_persent_tv);
            mCountDownView= (CountdownView) itemView.findViewById(R.id.countDownView);

        }

        public void bindData(LendYouXuanBean.DataBean.CurBorrowsBean itemInfo) {
            mItemInfo = itemInfo;

        }

        public void refreshTime() {
            if (null == mItemInfo || mCountDownView.getRemainTime() <= 0)
                return;
            mCountDownView.updateShow((Long.valueOf(mItemInfo.getTime_start()) - System.currentTimeMillis() / 1000 + mItemInfo.getCountdown()) * 1000);




        }

    }

    class EmptyHolder extends RecyclerView.ViewHolder {
        TextView nodata;

        RelativeLayout noDataLayout;
        public EmptyHolder(View itemView) {
            super(itemView);
        }
    }


    public interface OnRecyclerViewNoDataClickListener {
        void onRecyclerViewNoDataClick();
    }



    public void startRefreshTime() {
        if (!isCancel) return;

        if (null != mTimer) {
            mTimer.cancel();
        }

        isCancel = false;
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.post(mRefreshTimeRunnable);
            }
        }, 0, 1000);
    }

    public void cancelRefreshTime() {
        isCancel = true;
        if (null != mTimer) {
            mTimer.cancel();
        }
        mHandler.removeCallbacks(mRefreshTimeRunnable);
    }

    private Runnable mRefreshTimeRunnable = new Runnable() {
        @Override
        public void run() {
            if (mCountdownVHList.size() == 0) return;

            synchronized (mCountdownVHList) {
              long currentTime = System.currentTimeMillis()/1000;
                Log.i("restTime","currentTime"+currentTime+"-----");
                int key;
                for (int i = 0; i < mCountdownVHList.size(); i++) {
                    key = mCountdownVHList.keyAt(i);
                    AdapterLendRecycler.VideoViewHolder curMyViewHolder = mCountdownVHList.get(key);
                    long a=curMyViewHolder.getmCountDownView().getRemainTime()/1000;
                    if (a<=0) {
                        // 倒计时结束
//                        curMyViewHolder.getmItemInfo().setTime_start("0");

                        Log.i("restTime","倒计时结束");
                        mCountdownVHList.remove(key);
                        curMyViewHolder.getmItemInfo().setButton_status(STATUS_CHUJIE);
                        notifyDataSetChanged();

                    } else {
                        curMyViewHolder.refreshTime();
                    }

                }
                }
        }
    };
}
